//
//  NSData+Hex.m
//  blueteeth
//
//  Created by tom on 15/11/19.
//  Copyright © 2015年 tom. All rights reserved.
//

#import "NSData+Hex.h"

@implementation NSData (Hex)

//十六進位字串轉bytes，可以設定size，padding在左邊
+(NSData *)hexStrToNSData:(NSString *)data withSize:(NSInteger)size
{
    NSUInteger add = size*2 - data.length;
    if (add > 0) {
        NSString* tmp = [[NSString string] stringByPaddingToLength:add withString:@"0" startingAtIndex:0];
        data = [tmp stringByAppendingString:data];
    }
    return [self hexStrToNSData:data];
}

//十六進位字串轉bytes
+(NSData *)hexStrToNSData:(NSString *)hexStr
{
    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= hexStr.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* ch = [hexStr substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:ch];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}

@end
